package com.class5.springboot.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class DateUtils {

    protected static Logger log = LoggerFactory.getLogger(DateUtils.class);

    public static String getFormatDate(Date dateTime) {
        String formaStr = "";
        try {
            SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date now = dfs.parse(dfs.format(getNowDateTime()));
            Date temp = dfs.parse(dfs.format(dateTime));
            long between = (now.getTime() - temp.getTime()) / 1000;// 除以1000是为了转换成秒

            long dayDiff = between / (24 * 3600);
            long monthDiff = between / (24 * 3600 * 30);
            long hourDiff = between % (24 * 3600) / 3600;
            long minuteDiff = between % 3600 / 60;
            // long secondDiff = between%60/60;
            long yearDiff = between / (24 * 3600 * 30 * 10);
            if ((dayDiff == 0) && (monthDiff == 0) && (hourDiff == 0) && (minuteDiff == 0) && (between != 0)) {
                formaStr = String.valueOf(minuteDiff) + "秒钟前";
            } else if ((dayDiff == 0) && (monthDiff == 0) && (hourDiff == 0) && (minuteDiff != 0)) {
                formaStr = String.valueOf(minuteDiff) + "分钟前";
            } else if ((dayDiff == 0) && (monthDiff == 0) && (hourDiff != 0)) {
                formaStr = String.valueOf(hourDiff) + "小时前";
            } else if ((dayDiff != 0) && (monthDiff != 0) && (monthDiff < 12)) {
                formaStr = String.valueOf(monthDiff) + "个月前";
            } else if ((monthDiff == 0) && (dayDiff != 0)) {
                formaStr = String.valueOf(dayDiff) + "天前";
            } else if (monthDiff >= 12) {
                formaStr = String.valueOf(yearDiff) + "年前";
            } else {
                formaStr = "当前";
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return formaStr;
    }

    public static String getFormatDiffDate(Date dateTime) {
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd");
        String str = dfs.format(dateTime);
        try {
            SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date now = new Date();
            String nowStr = dfs.format(now) + " 23:59:59";
            String dateStr = dfs.format(dateTime) + " 23:59:59";
            long between = (sdfs.parse(dateStr).getTime() - sdfs.parse(nowStr).getTime()) / 1000;// 除以1000是为了转换成秒
            long dayDiff = between / (24 * 3600);
            if (dayDiff > 0) {
                str += "(还剩" + dayDiff + "天)";
            } else if (dayDiff == 0) {
                str += "(今天)";
            } else if (dayDiff < 0) {
                str += "(超期" + (-dayDiff) + "天)";
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return str;
    }

    public static String formatDate(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    /**
     * java计算两个时间相差（天、小时、分钟、秒）
     *
     * @param begin 开始时间
     * @param end   结束时间
     * @return
     */
    public static String getDiffDate(Timestamp begin, Timestamp end) {
        long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
        long nh = 1000 * 60 * 60;// 一小时的毫秒数
        long nm = 1000 * 60;// 一分钟的毫秒数
        long ns = 1000;// 一秒钟的毫秒数
        long diff;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        // 获得两个时间的毫秒时间差异
        diff = end.getTime() - begin.getTime();
        day = diff / nd;// 计算差多少天
        hour = diff % nd / nh;// 计算差多少小时
        min = diff % nd % nh / nm;// 计算差多少分钟
        sec = diff % nd % nh % nm / ns;// 计算差多少秒
        StringBuffer result = new StringBuffer();
        if (day != 0) {
            result.append(day).append('天');
        }
        if (hour != 0) {
            result.append(hour).append("小时");
        }
        if (min != 0) {
            result.append(min).append("分钟");
        }
        if (sec != 0) {
            result.append(sec).append('秒');
        }
        return result.toString();
    }

    /**
     * 输入一个时间到累加的一个时间之间的倒计时
     * @param starTime 起始时间
     * @param limitHour
     * @return
     */
    public static String getCountdownTime(Timestamp starTime, Long limitHour) {
        StringBuffer result = new StringBuffer();
        try {
            long nowDate = System.currentTimeMillis();
            long diff =starTime.getTime() + limitHour - nowDate;
            long countdown = diff / (1000 * 60);//获取倒计时（分钟）
            long day = countdown / (60 * 24);// 天
            long hour = countdown / 60 % 24;// 小时
            long min = countdown % 60;// 分钟
            result.append("剩余：");
            if (day > 0) {
                result.append(day).append('天');
            }
            if (hour > 0) {
                result.append(hour).append("小时");
            }
            if (min > 0) {
                result.append(min).append("分钟");
            }
        } catch (Exception e) {
            result.append("无法进行倒计时");
            log.error(e.getMessage(), e);
        }
        return result.toString();
    }

    /**
     * java计算两个时间相差（天）
     *
     * @param begin 开始时间
     * @param end   结束时间
     * @return
     */
    public static String getDiffDay(Timestamp begin, Timestamp end) {
        long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
        long diff;
        long day = 0;
        // 获得两个时间的毫秒时间差异
        diff = end.getTime() - begin.getTime();
        day = diff / nd;// 计算差多少天
        StringBuffer result = new StringBuffer();
        result.append(day).append('天');
        return result.toString();
    }

    /**
     * java计算两个时间相差（小时）
     *
     * @param begin 开始时间
     * @param end   结束时间
     * @return
     */
    public static Long getDiffHour(Timestamp begin, Timestamp end) {
        long nh = 1000 * 60 * 60;// 一小时的毫秒数
        long diff;
        // 获得两个时间的毫秒时间差异
        diff = end.getTime() - begin.getTime();
        return diff/nh;
    }

    /**
     * java计算两个时间相差（分钟）
     *
     * @param begin 开始时间
     * @param end   结束时间
     * @return
     */
    public static Long getDiffMinutes(Timestamp begin, Timestamp end) {
        long nh = 1000 * 60;// 一分钟的毫秒数
        long diff;
        // 获得两个时间的毫秒时间差异
        diff = end.getTime() - begin.getTime();
        return diff/nh;
    }

    /**
     * 取得当前时间(yyyy-MM-dd)
     *
     * @return Date
     * @throws ParseException
     */
    public static Date getNowDate() throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date dateTime = formatter.parse(getDayTime());
        return dateTime;
    }

    /**
     * 取得当前日期(yyyy-MM-dd HH:mm:ss)
     *
     * @return Date
     * @throws ParseException
     */
    public static Date getNowDateTime() throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dateTime = formatter.parse(getDayTime());
        return dateTime;
    }

    /**
     * 获取当前时间 HH一定要大写，小写的话，变成12小时日期制 format: yyyy-MM-dd HH:mm:ss
     *
     * @return String 格式:yyyy-MM-dd HH:mm:ss
     */
    public static String getDayTime() {
        Calendar calender = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        format.setLenient(false);
        String datetime = format.format(calender.getTime());
        return datetime;
    }

    /**
     * 获取当前时间 HH一定要大写，小写的话，变成12小时日期制 format: yyyy-MM-dd
     *
     * @return String 格式:yyyy-MM-dd
     */
    public static String getDay() {
        Calendar calender = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        format.setLenient(false);
        String datetime = format.format(calender.getTime());
        return datetime;
    }

    /**
     * 获取当前时间 HH一定要大写，小写的话，变成12小时日期制 format: yyyy-MM-dd
     *
     * @return String 格式:yyyy-MM-dd
     */
    public static String getDay1() {
        Calendar calender = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        format.setLenient(false);
        String datetime = format.format(calender.getTime());
        return datetime;
    }

    /**
     * 时间格式转换
     *
     * @param time
     * @param dateFormat
     * @return
     */
    public static String changeDateStr(Timestamp time, String dateFormat) {
        if (dateFormat == null || "".equals(dateFormat)) {
            dateFormat = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        format.setLenient(false);
        Date d = new Date();
        d.setTime(time.getTime());
        String datetime = format.format(d);
        return datetime;
    }

    public static String formatSimpleDate(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    public static String getFormatLongTime(Long time,String pattern){
        Date date = new Date(time);
        return formatDate(date,pattern);
    }

    public static String formatSimpleTimestamp(Timestamp timestamp) {
        return formatSimpleTimestamp(timestamp, "yyyy-MM-dd");
    }

    public static String formatSimpleTimestamp(Timestamp timestamp, String formatStr) {
        if (timestamp == null) {
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat(formatStr);//yyyy-MM-dd HH:mm:ss
        Date date = new Date(timestamp.getTime());
        return format.format(date);
    }

    /**
     * @param time
     * @param today
     * @return today.compareTo(time + 1天)
     */
    public static int checkTimeNextDay(Timestamp time, Date today) throws ParseException {
        if (today == null) today = new Date();
        today = DateUtils.parseSimpleDateStr(DateUtils.formatSimpleDate(today));
        Date valday = new Date(time.getTime());
        Calendar cal = Calendar.getInstance();
        cal.setTime(valday);
        cal.add(Calendar.DATE, 1);
        Date vday = cal.getTime();
        return today.compareTo(vday);
    }

    public static Date parseSimpleDateStr(String dateStr) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.parse(dateStr);
    }

    public static Date parse(Class clazz ,String dateStr){
        if(StringUtils.isTrimEmpty(dateStr)){
            return null;
        }
        try {
            SimpleDateFormat format = null;
            if(clazz.equals(java.sql.Date.class)){
                format = new SimpleDateFormat("yyyy-MM-dd");
                return new java.sql.Date(format.parse(dateStr.toString()).getTime());
            }else if(clazz.equals(java.sql.Timestamp.class)){
                format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return new java.sql.Timestamp(format.parse(dateStr.toString()).getTime());
            }
        }catch (ParseException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }


    public static Timestamp parse(String dateStr, String... patterns) {
        for (String pattern : patterns) {
            SimpleDateFormat format = new SimpleDateFormat(pattern);
            Long date;
            try {
                date = format.parse(dateStr).getTime();
                return new Timestamp(date);
            } catch (ParseException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public static Timestamp addTimestampDay(Timestamp tsm, int d) {
        Date date = new Date();
        date.setTime(tsm.getTime());
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, d);
        Date vday = cal.getTime();
        return new Timestamp(vday.getTime());
    }

    /**
     * Timestamp进行加减操作
     *
     * @param tsm
     * @param field :Calendar.YEAR,Calendar.MONTH,Calendar.DATE,Calendar.HOUR,Calendar.MINUTE,Calendar.SECOND
     * @param d
     * @return
     */
    public static Timestamp addTimestamp(Timestamp tsm, Integer field, Integer d) {
        Date date = new Date();
        date.setTime(tsm.getTime());
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(field, d);
        Date vday = cal.getTime();
        return new Timestamp(vday.getTime());
    }

    public static Date addDay(Date date, int d) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, d);
        return cal.getTime();
    }

    public static Long getDiffDay(Timestamp dateTime) {
        long dayDiff = 0;
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd");
        try {
            SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date now = new Date();
            String nowStr = dfs.format(now) + " 23:59:59";
            String dateStr = dfs.format(dateTime) + " 23:59:59";
            long between = (sdfs.parse(dateStr).getTime() - sdfs.parse(nowStr).getTime()) / 1000;// 除以1000是为了转换成秒
            dayDiff = between / (24 * 3600);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return dayDiff;
    }


    /**
     * 获得加减后的日期
     * @param date
     * @param field Calendar.YEAR,MONTH,DATE,HOUR,MINUTE,SECOND
     * @param value
     * @return
     */
    public static Date add(Date date, int field, int value) {
        Calendar calendar = calendar(date);
        calendar.add(field, value);
        return calendar.getTime();
    }

    private static Calendar calendar(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar;
    }

    public static Date truncateTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    public static Date strToDate(String strInput, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = sdf.parse(strInput);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * @param date
     * @param dayOfWeek @See Calendar.DAY_OF_WEEK
     * @return
     */
    public static boolean isDayOfWeek(Date date, int dayOfWeek) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DAY_OF_WEEK) == dayOfWeek;
    }

    /**
     * 根据年份 月份获得 月份第一天跟最后一天
     *
     * @param year
     * @param month
     */
    public static List<Timestamp> getFirstLastDays(Integer year, Integer month) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month - 1, cal.getMinimum(Calendar.DATE), 0, 0, 0);
        cal.set(Calendar.MILLISECOND, 0);
        Timestamp firstDate = new Timestamp(cal.getTimeInMillis());
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 999);
        Timestamp lastDate = new Timestamp(cal.getTimeInMillis());
        List dates = new ArrayList();
        dates.add(firstDate);
        dates.add(lastDate);
        return dates;
    }

    public static String[] getFirstlastDays(Timestamp startTime) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startTime);
        String[] back = new String[2];
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getMinimum(Calendar.DATE));
        back[0] = formatDate(calendar.getTime(), "yyyy年MM月dd日");
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DATE));
        back[1] = formatDate(calendar.getTime(), formatDate(calendar.getTime(), "yyyy年MM月dd日"));
        return back;
    }

    public static String[] getFirstlastDays(Date startTime, String pattern) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startTime);
        String[] back = new String[2];
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getMinimum(Calendar.DATE));
        back[0] = formatDate(calendar.getTime(), pattern);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DATE));
        back[1] = formatDate(calendar.getTime(), formatDate(calendar.getTime(), pattern));
        return back;
    }

    /**
     * 获取上个月的年月
     * @param currentYearMonth yyyyMM "201702"
     * @return  lastYearMonth "201701"
     * @throws Exception
     */
    public static String  getLastYearMonth(String currentYearMonth) throws  Exception{
        //获取上个月年月
        SimpleDateFormat sdf = new SimpleDateFormat ("yyyyMM");
        Date date = sdf.parse (currentYearMonth);
        Calendar calendar = Calendar.getInstance ();
        calendar.setTime (date);
        calendar.add(Calendar.MONTH, -1);
        String lastYearMonth = sdf.format (calendar.getTime ());
        return lastYearMonth;
    }

    /**
     * 获取某个月份的开始时间和结算时间
     *
     * @param month
     * @return
     */
    public static Timestamp[] getFirstAndLastDayOfMonth(String month) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.MONTH, Integer.valueOf(month) - 1);//Calendar 月份从0开始
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        c.set(Calendar.DAY_OF_MONTH, 1);
        Timestamp start = new Timestamp(c.getTimeInMillis());
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        c.set(Calendar.MILLISECOND, 999);
        c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DATE));
        Timestamp end = new Timestamp(c.getTimeInMillis());
        Timestamp[] times = {start, end};
        return times;
    }

    /**
     * 获取给定日期月份的第一天
     *
     * @param date
     * @return
     */
    public static Timestamp getFirstDayOfMonth(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.DAY_OF_MONTH, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return new Timestamp(c.getTimeInMillis());
    }

    /**
     * 获取给定日期月份的最后一天
     *
     * @param date
     * @return
     */
    public static Timestamp getLastDayOfMonth(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.MONTH, 1);
        c.set(Calendar.DAY_OF_MONTH, 1);
        c.add(Calendar.DAY_OF_MONTH, -1);
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        c.set(Calendar.MILLISECOND, 999);
        return new Timestamp(c.getTimeInMillis());
    }

    /**
     * 校验时间字符串格式是否符合要求
     *
     * @param timeStr
     * @param pattern
     * @return
     */
    public static Boolean validateTimeStrFormat(String timeStr, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            sdf.parse(timeStr);
            return true;
        } catch (ParseException e) {
            //e.printStackTrace();
        }

        return false;
    }

    /**
     * 获取指定间隔的开始结束时间区间
     *
     * @param intervalMinutes
     */
    public static List<Timestamp> getIntervalStartEndTime(Timestamp timestamp, Integer intervalMinutes) {
        Calendar calendar = Calendar.getInstance();
        if (timestamp != null) {
            try {
                String formatStr = "yyyy-MM-dd HH:mm:ss.SSS";
                calendar.setTime(new SimpleDateFormat(formatStr).parse(formatSimpleTimestamp(timestamp, formatStr)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        int minute = calendar.get(Calendar.MINUTE);
        minute = (minute / intervalMinutes) * intervalMinutes;
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        //calendar.add(Calendar.MINUTE, -intervalMinutes);
        Timestamp startTime = new Timestamp(calendar.getTimeInMillis());

        calendar.add(Calendar.MINUTE, +intervalMinutes);
        calendar.add(Calendar.MILLISECOND, -1);
        Timestamp endTime = new Timestamp(calendar.getTimeInMillis());

        List dates = new ArrayList();
        dates.add(startTime);
        dates.add(endTime);
        return dates;
    }

    /*public static List<Timestamp> getIntervalStartEndTime(Integer intervalMinutes) {
        return getIntervalStartEndTime(null, intervalMinutes);
    }*/

    /**
     * 获取开始时间和结束时间（yyyy-MM）
     *
     * @param from
     * @param to
     * @param pattern
     * @return
     */
    public static Timestamp[] getFirstAndLastDayUnderPattern(String from, String to, String pattern) {
        SimpleDateFormat dateformat = new SimpleDateFormat(pattern);
        try {
            //开始时间
            Calendar cf = Calendar.getInstance();
            cf.setTime(dateformat.parse(from));
            cf.set(Calendar.DAY_OF_MONTH, 1);//1号
            cf.set(Calendar.HOUR_OF_DAY, 0);//0时
            cf.set(Calendar.MINUTE, 0);//0分
            cf.set(Calendar.SECOND, 0);//0秒
            cf.set(Calendar.MILLISECOND, 0);

            //结束时间
            Calendar ct = Calendar.getInstance();
            ct.setTime(dateformat.parse(to));
            ct.set(Calendar.DAY_OF_MONTH, ct.getActualMaximum(Calendar.DAY_OF_MONTH));//本月最后一天
            ct.set(Calendar.HOUR_OF_DAY, 23);//0时
            ct.set(Calendar.MINUTE, 59);//0分
            ct.set(Calendar.SECOND, 59);//0秒
            ct.set(Calendar.MILLISECOND, 999);

            Timestamp fromTime = new Timestamp(cf.getTime().getTime());
            Timestamp toTime = new Timestamp(ct.getTime().getTime());
            Timestamp[] times = {fromTime, toTime};
            return times;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取开始时间和结束时间
     *
     * @param
     * @return
     */
    public static Timestamp getDayOfLastSecond(Timestamp time) {
        //开始时间
        Calendar cf = Calendar.getInstance();
        cf.setTimeInMillis(time.getTime());
        cf.set(Calendar.HOUR_OF_DAY, 23);//0时
        cf.set(Calendar.MINUTE, 59);//0分
        cf.set(Calendar.SECOND, 59);//0秒
        cf.set(Calendar.MILLISECOND, 999);
        return new Timestamp(cf.getTime().getTime());
    }

    /**
     * 获取本月的结束时间（yyyy-MM）
     *
     * @param dateStr
     * @return
     */
    public static String getLastDayYearMonth(String dateStr, String formate) {
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM");
        try {
            //结束时间
            Calendar ct = Calendar.getInstance();
            ct.setTime(dateformat.parse(dateStr));
            ct.set(Calendar.DAY_OF_MONTH, ct.getActualMaximum(Calendar.DAY_OF_MONTH));//本月最后一天
            ct.set(Calendar.HOUR_OF_DAY, 23);//0时
            ct.set(Calendar.MINUTE, 59);//0分
            ct.set(Calendar.SECOND, 59);//0秒
            ct.set(Calendar.MILLISECOND, 999);
            return DateUtils.formatDate(ct.getTime(), formate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *获取两个时间区间的所有月份
     *
     * @param startDate 最小时间
     * @param endDate 最大时间
     * @return 日期集合 格式为 年月 例201709
     * @throws Exception
     */
    public static JSONArray getMonthBetween(String startDate, String endDate) throws Exception {
        JSONArray data = new JSONArray();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");//格式化为年月
        SimpleDateFormat sdfStr = new SimpleDateFormat("yyyy年MM月");//格式化为年月

        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        min.setTime(sdf.parse(startDate));
        min.add(Calendar.MONTH,-1);

        max.setTime(sdf.parse(endDate));

        Calendar curr = min;
        while (min.before(max)) {
            JSONObject item = new JSONObject();
            curr.add(Calendar.MONTH, 1);
            item.put("dateStr",sdfStr.format(curr.getTime()));
            item.put("dateCode",sdf.format(curr.getTime()));
            data.add(item);

        }
        return data;
    }
    /**
     *获取两个时间区间的所有月份
     *
     * @param startDate 最小时间
     * @param endDate 最大时间
     * @return 日期集合 格式为 年月 例201709
     * @throws Exception
     */
    public static List<String> getMonthBetweenList(String startDate, String endDate) throws Exception {
        List<String> data = new ArrayList<>();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");//格式化为年月
        SimpleDateFormat sdfStr = new SimpleDateFormat("yyyy年MM月");//格式化为年月

        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        min.setTime(sdf.parse(startDate));
        min.add(Calendar.MONTH,-1);

        max.setTime(sdf.parse(endDate));

        Calendar curr = min;
        while (min.before(max)) {
            curr.add(Calendar.MONTH, 1);
            data.add(sdf.format(curr.getTime()));
        }
        return data;
    }

    /*
     * 将时间转换为时间戳
     */
    public static String datetimeToStamp(String s) throws ParseException{
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }

    /*
     * 将时间转换为时间戳
     */
    public static String dateToStamp(String s) throws ParseException{
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }

    /*
     * 将时间戳转换为时间
     */
    public static String stampToDatetime(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    /*
     * 将时间戳转换为时间
     */
    public static String stampToDate(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    /*
     * Timestamp转化为 dateType:1日期   2时间
     */
    public static String TimestampToDateString(Timestamp s,String dateType){
        String time = s.toLocalDateTime()+"";
        if (dateType == null || "".equals(dateType)) {
            dateType = "1";
        }
        if(dateType.equals("1")){
            time = time.substring(0,time.indexOf("T"));
        }
        if(dateType.equals("2")){
            time.replace("T"," ");
        }
        return time;
    }

    /**
     * 获得几个月之前的年月
     * @param yearMonth 查询年月
     * @param ago 几个月前
     * @return
     */
    public static Integer getYearMonthAgo(Integer yearMonth, Integer ago){
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMM");
        try {
            Calendar calendar = Calendar.getInstance(); //得到日历
            calendar.setTime(dateformat.parse(yearMonth+""));//把当前时间赋给日历
            calendar.add(calendar.MONTH, -ago);
            return Integer.valueOf(dateformat.format(calendar.getTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}